<template>
  <base-breadcrumb>
    <a-card style="margin-top:12px">
      <title-name title="设计策划书审核" />
      <div class="title">
        否决项
      </div>
      <a-table
        :columns="columns"
        :data-source="tableData"
        bordered
        :pagination="false"
      >
        <!-- CheckBox选择框 -->
        <template
          slot="checkbox"
          slot-scope="text, record"
        >
          <a-checkbox @change="changeCheckbox(record)" />
        </template>
        <!-- 序号 -->
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
      </a-table>
      <div class="title">
        评分项
      </div>
      <a-table
        :columns="columnsScore"
        :data-source="ScoreTableData"
        bordered
        :pagination="false"
      >
        <!-- 序号 -->
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <template
          slot="score"
          slot-scope="text, record"
        >
          <!-- <a @click="editScore(record)">评分</a> -->
          <BaseInputNumber
            v-model="record.score"
            style="width:100px"
            :max="getMaxValue(record)"
            :min="0"
            placeholder="请评分"
            @keydown="handleInput2"
            @blur="changeScore()"
          />
        </template>
        <template
          slot="information"
          slot-scope="text, record"
        >
          <!-- <a @click="editScore(record)">评分</a> -->
          <BaseTextarea
            v-model="record.information"
            :disabled="record.disabled"
            placeholder="请输入评分说明"
          />
        </template>
      </a-table>
      <!-- <BaseAudit :callbackFn="validateForm" :submitData="childSubmitData">
            <template v-slot:extraResult>
                <a-descriptions class="mb20" title="">
                    <a-descriptions-item label="审核总分">
                        {{totalScore}}
                    </a-descriptions-item>
                    <a-descriptions-item label="审核结果">
                        {{result}}
                    </a-descriptions-item>
                </a-descriptions>
            </template>
        </BaseAudit> -->
      <base-breadcrumb
        title="审批"
        subtitle="审批"
        :breadcrumb="{ name: '审批' }"
      >
        <title-name :title="processName + '-' + taskName" />
        <a-card
          :body-style="{ padding: '24px 32px' }"
          :bordered="false"
        >
          <title-name title="节点信息" />
          <slot name="extraResult" />
          <a-descriptions
            class="mb20"
            title=""
          >
            <a-descriptions-item label="审核总分">
              {{ totalScore }}
            </a-descriptions-item>
            <a-descriptions-item label="审核结果">
              {{ auditResult }}
            </a-descriptions-item>
            <a-descriptions-item label="当前节点">
              {{ taskName }}
            </a-descriptions-item>
            <a-descriptions-item label="审批人">
              {{ currentUser.name }}
            </a-descriptions-item>
            <a-descriptions-item label="审批时间">
              {{ currentTime }}
            </a-descriptions-item>
          </a-descriptions>
          <div
            v-if="assignType"
            class="mb20"
          >
            <title-name title="指派人员" />
            <a-form-model
              ref="ruleForm"
              :model="form"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
              <a-row :gutter="24">
                <a-col
                  v-if="assignType == '3'"
                  :md="12"
                  :sm="12"
                  class="col"
                >
                  <a-form-model-item
                    label="组织"
                    prop="orgSelectedName"
                  >
                    <TreeSelectOrganization
                      v-model="form.orgSelectedName"
                      :org-selected-value.sync="form.orgSelectedName"
                      :org-selected-label.sync="form.orgSelectedLabel"
                      :children-node="childrenNode"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                  v-if="assignType == '3'"
                  :md="12"
                  :sm="12"
                  class="col"
                >
                  <a-form-model-item
                    label="岗位"
                    prop="jobsSelectedName"
                  >
                    <Jobs
                      v-model="form.jobsSelectedName"
                      :selected-value.sync="form.jobsSelectedName"
                      :tree-checkable="treeCheckable"
                      :add-titel="form.orgSelectedLabel[0]"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                  v-else
                  :md="12"
                  :sm="12"
                  class="col"
                >
                  <a-form-model-item
                    label="指派人员"
                    prop="respEmployeeId"
                  >
                    <OrgStaffAsync
                      v-model="form.respEmployeeId"
                      :selected-value.sync="form.respEmployeeId"
                      :tree-checkable="assignType != '1'"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
          <title-name title="审批意见" />
          <a-form
            ref="form1"
            :form="form"
          >
            <a-row :gutter="24">
              <a-col
                :md="24"
                :sm="24"
              >
                <a-form-item>
                  <BaseTextarea
                    v-model="opinions"
                    style="width: 100%"
                    placeholder="请填写审批意见"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <slot name="extraMiddle" />
            <a-row
              :gutter="24"
              class="overfloat"
            >
              <a-col
                :md="24"
                :sm="24"
              >
                <div class="floatRight">
                  <!-- <a-button type="success" style="margin-right: 20px" @click="handleDetail" v-if="!!detailUrl"
                                >查看详情</a-button
                            >
                            <a-button type="primary" style="margin-right: 20px" @click="handelUnApproval"
                                >审批不通过</a-button
                            > -->
                  <a-button
                    type="primary"
                    @click="handelApproval"
                  >
                    提交审批结果
                  </a-button>
                </div>
              </a-col>
            </a-row>
          </a-form>

          <title-name title="审批流程信息" />
          <!-- <a-spin tip="流程信息加载中..." > -->
          <div class="btns-wrapp mb20">
            <a-button
              type="primary"
              @click="visibleState.auditProcess = true"
            >
              审批流程图
            </a-button>
          </div>
          <a-table
            :columns="columnApprove"
            :data-source="approveInfos"
            bordered
          >
            <span
              slot="serial"
              slot-scope="text, record, index"
            >{{ index + 1 }}</span>
          </a-table>
          <!-- </a-spin> -->
        </a-card>
        <slot name="extraAfter" />
      </base-breadcrumb>
    </a-card>

    <a-card
      :bordered="false"
      style="over-flow:scroll"
    >
      <title-name title="设计策划书信息" />
      <a-form-model
        ref="ruleForm"
        :model="form"
        :label-col="{lg: {span: 6}, sm: {span:6}}"
        :wrapper-col="{lg: {span: 18}, sm: {span: 18} }"
      >
        <a-row>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="分公司"
              prop="branchId"
            >
              <!-- <a-select :disabled="type=='view'"   v-model="form.branchId" >
              <a-select-option v-for="item in company" :key="item.orgId" :value="item.orgId">{{item.orgName}}</a-select-option>
            </a-select> -->
              <BaseInput
                v-model="form.branchCompany"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="项目名称"
              prop="projectId"
            >
              <!-- <a-select :disabled="type=='view'" @focus="handleChangeCompany"   @change="changeProjectType(form.projectId)" v-model="form.projectId" >
              <a-select-option v-for="item in projectLists" :key="item.code" :value="item.code">{{item.name}}
              </a-select-option>
            </a-select> -->
              <BaseInput
                v-model="form.project"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="项目设计管理类别"
              prop="designType"
            >
              <BaseInput
                v-model="form.designType"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="设计策划书名称"
              prop="name"
            >
              <BaseInput
                v-model="form.name"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="双优化立项计划表"
              prop="optimization"
            >
              <BaseInput
                v-model="form.optimization"
                disabled
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="创建人"
              prop="user"
            >
              <BaseInput
                v-model="form.person"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="创建时间"
              prop="user"
            >
              <BaseInput
                v-model="form.time"
                disabled
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <title-name title="设计策划书/盈亏分析表" />

      <!-- <a-upload  name="file" :showUploadList='false' :before-upload="beforeUpload" @change="handleChanges">
          <a-button v-if="type !='view'" type="primary" style="margin-bottom: 20px;"><a-icon type="upload"  style="font-size: 1.2rem" />上传</a-button>
        </a-upload> -->
      <!-- <a-button v-if="type !='view'" type="" style="margin-bottom: 20px;margin-left: 20px" @click="deleteExteriorFile()"><a-icon   style="font-size: 1.2rem" />删除</a-button> -->

      <a-table
        bordered
        :columns="columnAssment"
        :data-source="dataAssement"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <span
          slot="action"
          slot-scope="text, record"
        >
          <a
            :href="'/api/ycloud-file-center/oper/download?access_token='+token+'&fileId='+record.fileId"
            target="_parent"
          >导出</a>
          <a-divider type="vertical" />
          <a
                  href="javascript:"
                  @click="$filePreview(record)"
          >预览</a>
        </span>
      </a-table>
    </a-card>
    <ApprovalDetails
      :title="'审批流程信息'"
      :business-id="this.id"
      :visible="visibleState.auditProcess"
      @cancel="visibleState.auditProcess = false"
      @confirm="visibleState.auditProcess = false"
    />
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getProjectType } from '@/api/design/plotsPlan'
import { planList } from '@/api/technical/optimizationPlan'
import {
  getplotsManage,
  getplotsManageTotal,
  getplotsManageDetail,
  getplotsManageAdd,
  submitScoreForm
} from '@/api/design/designManage'
import { themeChoose } from '@/mixin/mixin'
import DynamicForm from '@/components/DynamicForm/index.js'
import cloneDeep from 'lodash.clonedeep'
import FooterToolBar from '@/components/FooterToolbar'
import { getProcessNodeList, completeTask } from '@/api/process'
import { getOrgEmployeesListBy } from '@/api/commons'
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import OrgStaffAsync from '@/components/TreeSelectOrganization/orgStaffAsync.vue'
import Jobs from '@/components/TreeSelectOrganization/jobs'
import moment from 'moment'
import ApprovalDetails from '@/components/approvalDetails'
import Vue from 'vue'

const columnApprove = [
  {
    title: '序号',
    width: 80,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '审批人',
    dataIndex: 'userName'
  },
  {
    title: '审批时间',
    dataIndex: 'createTime'
  },
  {
    title: '节点名称',
    dataIndex: 'taskName'
  },
  {
    title: '滞留时间',
    dataIndex: 'durationInMillis'
  },
  {
    title: '审批意见',
    dataIndex: 'formData.opinions'
  }
]

const columnAssment = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '35%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '35%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  mixins: [themeChoose],
  components: {
    // STable,
    // DynamicForm,
    // FooterToolBar,
    TreeSelectOrganization,
    Jobs,
    ApprovalDetails,
    OrgStaffAsync
  },
  data() {
    return {
      visibleState: {
        auditProcess: false
      },
      token: '',
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return planList(requestParameters).then((res) => {
          return res
        })
      },
      selectedRowKeys: '',
      selectedRows: '',
      type: '',
      columnApprove,
      scorecount: '',
      scoreInformation: '',
      formAdd: {},
      columnAssment,
      dataAssement: [],
      totalScore: '',
      result: '',
      // 附件上传
      listUrl: '',
      deleteUrl: '',
      uploadList: ' ',
      reqMethod: 'post',
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      businessId: '',
      designType: '',
      opinions: '',
      detailUrl: null, //详情地址
      tableData: [],
      vetoHeaderId: '',
      scoreVisible: false,
      confirmLoading: false,
      id: '',
      name: '',
      status: '',
      columns: [],
      columnsScore: [],
      ScoreTableData: [],
      contentList: [],
      defaultData: {},
      formDatas: {},
      pageType: '',
      jobsList: [],
      visible: false,
      user: '',
      form: {
        orgSelectedName: '',
        orgSelectedLabel: '',
        jobsSelectedName: undefined, //岗位
        respEmployeeId: undefined, //人员
        vetoList: []
      },
      treeCheckable: true,

      childrenNode: 'jobs',

      flowRequesting: false,

      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目
      rules: {
        optimization: [{ required: true, message: '请关联双优化立项计划表', trigger: 'change' }],
        branchId: [{ required: true, message: '请选择单位名称', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }]
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    },
    auditResult() {
      if (this.form.vetoList && this.form.vetoList.length) {
        return '不合格'
      }
      if (this.totalScore < 80) {
        return '不合格'
      } else if (this.totalScore >= 80 && this.totalScore < 90) {
        return '良好'
      } else if (this.totalScore >= 90) {
        return '优秀'
      } else {
        return ''
      }
    }
  },
  created() {
    // 获取登录人名称
    this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
    this.id = this.$route.query.id
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.getplotsManageDetail()
    const { type, code, level, btype, businessId, procInstId, name, processName, detailUrl, taskId, taskDefKey } =
      this.$route.query
    if (type) {
      this.assignType = type
      this.assignCode = code
      this.assignLevel = level
      this.businessType = btype
    }
    this.id = businessId
    if (!this.id) {
      this.$error({ content: '无指定业务ID，将自动关闭' })
      setTimeout(() => {
        window.close()
      }, 1500)
      return
    }
    this.procInstId = procInstId
    this.taskName = decodeURIComponent(name)
    this.processName = decodeURIComponent(processName)
    document.title = this.processName + '-' + this.taskName
    if (detailUrl) {
      this.detailUrl = decodeURIComponent(detailUrl)
    }
    this.taskId = taskId
    this.taskDefKey = taskDefKey
    this.currentTime = moment().format('YYYY-MM-DD HH:mm')
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    //获取流程节点执行情况
    this.getProcessNodes()
  },
  methods: {
    handleInput2(e) {
      // 通过正则过滤小数点后两位
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,1})/g)[0] || null
    },
    // 获取输入项的最大允许值
    getMaxValue(data) {
      const targetData = this.columnsScore.find((item) => item.code === '4') // 考核评分列
      return (targetData && Number(data[targetData['dataIndex']])) || 0
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    handleDetail() {
      // const token = Vue.getAcloudProvider().getAccessToken();
      let routeData = this.$router.resolve({
        path: this.detailUrl,
        query: { businessId: this.id, businessType: this.$route.query.businessType || '', id: this.id, type: 'approve' }
      })
      window.open(routeData.href, '_blank')
    },
    submit(reject) {
      const data = {
        formData: {
          opinions: this.opinions,
          reject,
          projectId: ''
        },
        assignTypeEnum: this.assignType, //指派类型
        assgins: this.form.respEmployeeId, //人员
        groupEnum: this.form.jobsSelectedName, //岗位
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: this.currentUser.id
      }
      const variable = {}
      // return;
      if (reject) {
        variable.reject = true
      }

      data.variables = {
        ...variable,
        ...this.submitData // 特殊流程的数据，转交给审批
      }
      return completeTask(data)
        .then((res) => {
          if (res.status === 200) {
            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch((err) => {
          return err
        })
    },
    handelUnApproval() {
      const callbackFn = this.callbackFn
      if (callbackFn && !callbackFn('unApproval')) return
      // 审批不通过
      const _this = this
      if (!_this.opinions) {
        _this.$warning({ content: '请填写审批意见' })
        return
      }
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(true)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },

    handelApproval() {
      let arr = []
      let isTrue = false

      this.ScoreTableData.forEach((item) => {
        if (item.score == undefined && item.disabled !== true) {
          isTrue = true
        }
        arr.push({
          id: item.id,
          scoreIns: item.information,
          scoreCont: item.score
        })
      })

      if (isTrue) {
        this.$warning({ content: '请将评分信息填写完整再提交' })
        return
      }

      const _this = this
      if (!_this.opinions) {
        _this.$warning({ content: '请填写审批意见' })
        return
      }
      let newData = JSON.parse(JSON.stringify(arr).replace(/scoreIns/g, this.scoreInformation))
      let datas = JSON.parse(JSON.stringify(newData).replace(/scoreCont/g, this.scorecount))
      this.contentList = datas
      let submitForm = []
      submitForm.push({
        id: this.form.id,
        vetoList: this.form.vetoList,
        contentList: this.contentList
      })
      console.log(JSON.stringify(submitForm[0]))
      submitScoreForm(submitForm[0]).then((res) => {
        if (res.code == 200 || res.data.code == 200) {
          if ((submitForm[0].vetoList && submitForm[0].vetoList.length) || _this.totalScore < 80) {
            const callbackFn = this.callbackFn
            if (callbackFn && !callbackFn('unApproval')) return
            // 审批不通过
            const _this = this
            if (!_this.opinions) {
              _this.$warning({ content: '请填写审批意见' })
              return
            }
            const confirmWin = this.$confirm({
              title: '警告提醒！',
              content: '确定审批不通过？',
              okType: 'danger',
              onOk() {
                return new Promise((resolve, reject) => {
                  _this
                    .submit(true)
                    .then(() => {
                      resolve()
                      confirmWin.destroy()
                    })
                    .catch(() => reject)
                }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
              },
              onCancel() {}
            })
          } else {
            const callbackFn = this.callbackFn
            if (callbackFn && !callbackFn('approval')) return
            const confirmWin = this.$confirm({
              title: '警告提醒！',
              content: '确定审批通过？',
              okType: 'danger',
              onOk() {
                return new Promise((resolve, reject) => {
                  _this
                    .submit(false)
                    .then(() => {
                      resolve()
                      confirmWin.destroy()
                    })
                    .catch(() => reject)
                }).catch(() => {
                  this.$error({ content: '审批提交失败，请稍后重试' })
                })
              },
              onCancel() {}
            })
          }
        }
      })
    },
    openToTable() {
      this.visible = true
      this.planList()
    },
    changeScore(value) {
      let arr = []
      let obj = 2
      this.ScoreTableData.forEach((item) => {
        if (item.score) {
          arr.push(parseFloat(item.score))
        }
      })
      this.totalScore = eval(arr.join('+'))
      this.totalScore = parseFloat(this.totalScore).toFixed(2)
      if (this.totalScore == undefined) {
        this.totalScore = 0
      }
    },
    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then((res) => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map((d) => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds }).then((employees) => {
              this.flowRequesting = false
              res.data.forEach((r) => {
                employees.data.some((e) => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })
              this.approveInfos = res.data
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    },
    getplotsManageDetail() {
      if (this.id) {
        getplotsManageDetail({ id: this.id }).then((res) => {
          this.form = res.data
          if (res.data.fileIdsInfo) {
            this.dataAssement = res.data.fileIdsInfo
          }

          this.form.branchId = res.data.branchCompanyId
          // 否决项
          this.columns = res.data.vetoHeader
          this.tableData = res.data.vetoContent
          this.columns.unshift({
            dataIndex: 'serial',
            formId: null,
            title: '序号',
            code: '0',
            sort: 0,
            inputType: null,
            scopedSlots: { customRender: 'serial' }
          })
          let obj = {}
          this.columns.forEach((item) => {
            obj = this.columns.filter((items) => items.title == '是否否决')
          })
          this.vetoHeaderId = obj[0].dataIndex
          obj[0].scopedSlots = { customRender: 'checkbox' }
          // let obj =  {
          //   "dataIndex": "checkbox",
          //   "formId": null,
          //   "title": "是否否决",
          //   "code": "0",
          //   "sort": 0,
          //   "inputType": null,
          //   scopedSlots: { customRender: 'checkbox' }
          // }
          // this.columns.push(obj)
          // 评分项
          this.columnsScore = res.data.scoreHeader
          this.ScoreTableData = res.data.scoreContent
          this.formDatas = cloneDeep(res.data.scoreHeader)
          this.columnsScore.unshift({
            dataIndex: 'serial',
            formId: null,
            title: '序号',
            code: '0',
            sort: 0,
            inputType: null,
            scopedSlots: { customRender: 'serial' }
          })
          // this.columnsScore.push({
          //   "dataIndex": "serial",
          //   "formId": null,
          //   "title": "评分",
          //   "code": "0",
          //   "sort": 0,
          //   "inputType": null,
          //   scopedSlots: { customRender: 'score' }
          // })
          let objScore = {}
          this.columnsScore.forEach((item) => {
            objScore = this.columnsScore.filter((items) => items.title == '评分')
          })
          objScore[0].scopedSlots = { customRender: 'score' }
          this.scorecount = objScore[0].dataIndex

          let information = {}
          this.columnsScore.forEach((item) => {
            information = this.columnsScore.filter((items) => items.title == '评分说明')
          })
          information[0].scopedSlots = { customRender: 'information' }
          this.scoreInformation = information[0].dataIndex
        })
      }
    },
    planList() {
      planList({ pageSize: 10, pageNo: 1, query: { project: this.form.projectId } }).then((res) => {
        this.tableData = res.data[0].doubleOptimizationTypeVO
        this.formAdd = res.data[0]
      })
    },
    changeCheckbox(record) {
      const vetoList = this.form.vetoList || []
      const index = vetoList.findIndex((item) => item.id === record.id)
      if (index > -1) {
        vetoList.splice(index, 1)
      } else {
        vetoList.push({
          id: record.id,
          [this.vetoHeaderId]: '是'
        })
      }
      this.$set(this.form, 'vetoList', vetoList)
      // 选择否决项禁用评分项
      if (this.form.vetoList.length > 0) {
        this.ScoreTableData = this.ScoreTableData.map((el) => {
          el.disabled = true
          return el
        })
      } else {
        this.ScoreTableData = this.ScoreTableData.map((el) => {
          el.disabled = false
          return el
        })
      }
    },
    saveForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.form.status = '0'
          getplotsManageAdd(this.form).then((res) => {
            if (res.code == '200') {
              this.$router.push('/project/design/plotsManage')
              this.$message.success('新增成功')
            }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    submitScoreForm() {
      let arr = []
      this.ScoreTableData.forEach((item) => {
        arr.push({
          id: item.id,
          scoreIns: item.information,
          scoreCont: item.score
        })
      })
      let newData = JSON.parse(JSON.stringify(arr).replace(/scoreIns/g, this.scoreInformation))
      let datas = JSON.parse(JSON.stringify(newData).replace(/scoreCont/g, this.scorecount))
      this.contentList = datas
      let submitForm = []
      submitForm.push({
        id: this.form.id,
        vetoList: this.form.vetoList,
        contentList: this.contentList
      })
      submitScoreForm(submitForm[0]).then((res) => {
        if (res.code == '200') {
          this.$message.success('提交审核成功')
          this.$router.push('/project/design/plotsManage')
        }
      })
    },
    saveSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.form.status = '1'
          getplotsManageAdd(this.form).then((res) => {
            if (res.code == '200') {
              this.$router.push('/project/design/plotsManage')
              this.$message.success('提交成功')
            }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    goBack() {
      this.$multiTab.close(this.$route.fullpath)
    },
    changeProjectType(value) {
      let arr = []
      arr.push(value)
      getProjectType({ projectIds: arr }).then((res) => {
        this.form.num = res.data[0].projectNumber
        this.form.designType = res.data[0].designTypeName
        this.form.designTypeId = res.data[0].designTypeId
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    editScore(record) {
      this.scoreVisible = true
      this.defaultData = record
    },
    handleOk() {
      this.scoreVisible = false
      let ids = []
      this.ScoreTableData.forEach((item) => {
        ids = this.ScoreTableData.filter((items) => items.id == item.id)
      })
      // this.form.optimization = this.formAdd.name
      // this.form.optimizationId = this.formAdd.id
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>

<style scoped>
.input {
  width: 100%;
}
.footer {
  float: right;
  margin-right: 10px;
}
.footer button {
  margin-left: 10px;
}
.title {
  border-left: 4px solid #1890ff;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
  padding-left: 10px;
  height: 18px;
  line-height: 20px;
  margin-left: 20px;
  margin-top: 20px;
}
</style>
